$(function(){
  $('#add-category').click(function() {
    $('#add-category-modal').modal();
    var that = $('#add-category-modal');

    $('#add-category-modal').on('hidden', function () {
      var data = {'cname':'', 'ename':'', 'tag':''};
        for (k in data) {
        $('#add-category-modal input[name='+k+']').val('');
      }
      $('#add-category-modal .msg').empty();
    })
  
    $('#add-category-modal input').focus(function() {
      $('#add-category-modal .msg').empty();
    });

    $('#add-category-modal a.save').unbind();
    $('#add-category-modal a.save').click(function() {
      var data = {'cname':'', 'ename':'', 'tag':''};
        for (k in data) {
        data[k] = $('#add-category-modal input[name='+k+']').val();
      }
    
      $.post('/product/category/', data, function(ret) {
        if (ret.code == code.succ) {
          $('#add-category-modal').modal('hide');
          window.location.reload();
        } else {
          $('#add-category-modal div.msg').html(ret.msg);
        }
      }, 'json');
    });
  });


  $('a.delete').click(function() {
    if (confirm('确定要删除吗?')) {
    var that = $(this);
    var data = {'id':''};
    data.id = $(this).attr('data-id');
    $.post('/product/delete_category/', data, function(ret) {
      if (ret.code == code.succ) {
        that.parent().parent().fadeOut('slow');
      } else {
        alert('删除失败');
      }
    }, 'json');
    }
  });

  $('a.edit').click(function() {
    $('#edit-category-modal').modal();
    var that = $(this);

    $('#edit-category-modal').on('hidden', function () {
      var data = {'cname':'', 'ename':'', 'id':'', 'tag':''};
        for (k in data) {
        $('#edit-category-modal input[name='+k+']').val('');
      }
      $('#edit-category-modal .msg').empty();
    })
  
    $('#edit-category-modal input').focus(function() {
      $('#edit-category-modal .msg').empty();
    });


    var data = {'cname':'', 'ename':'', 'id':'', 'tag':''};
      for (k in data) {
      $('#edit-category-modal input[name='+k+']').val(that.attr('data-'+k));
    }

    $('#edit-category-modal a.save').unbind();
    $('#edit-category-modal a.save').click(function() {
      var data = {'cname':'', 'ename':'', 'id':'', 'tag':''};
        for (k in data) {
        data[k] = $('#edit-category-modal input[name='+k+']').val();
      }
      data.id = that.attr('data-id');
    
      $.post('/product/category_edit/', data, function(ret) {
        if (ret.code == code.succ) {
          $('#edit-category-modal').modal('hide');
          window.location.reload();
        } else {
          $('#edit-category-modal div.msg').html(ret.msg);
        }
      }, 'json');
    });
  });

});
